package com.bsi.com.bsi.dao;

import com.bsi.com.bsi.dto.PermissionDto;
import com.bsi.com.bsi.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserDao
 * @Author LiuSong
 * @Date 2020/8/13 9:21
 * @Version 1.0
 * @Description
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 根据用户名查询用户
    public UserDto findUserByName(String username) {
        String sql = "select id,username,password,fullname from t_user where username = ?";
        List<UserDto> query = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (query != null && query.size() == 1) {
            return query.get(0);
        }
        return null;
    }

    // 根据 userId查询用户权限
    public List<String> findPermissionByUserId(String userId) {
        String sql = "SELECT * FROM t_permission WHERE id IN(\n" +
                "SELECT permission_id FROM t_role_permission WHERE role_id IN(\n" +
                "\tSELECT role_id FROM t_user_role WHERE user_id = ? \n" +
                ")\n" +
                ")";

        List<PermissionDto> query = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        return query.stream().map(permissionDto -> permissionDto.getCode()).collect(Collectors.toList());
    }
}
